﻿using KnifeZ.XamarinDomain.Models;
using SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace KnifeZ.XamarinDomain
{
    public class DataContext
    {
        #region 通用方法单例
        private static SQLiteAsyncConnection instance;
        private static readonly object LockHelper = new object();
        /// <summary>
        /// 公共方法集实例
        /// </summary>
        public static SQLiteAsyncConnection Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (LockHelper)
                    {
                        if (instance == null)
                        {
                            instance = new SQLiteAsyncConnection(
                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    Consts.DataBaseName));
                        }
                    }
                }
                return instance;
            }
        }

        /// <summary>
        /// 刷新单例
        /// </summary>
        public static void RefreshInstance()
        {
            instance = null;
        }


        /// <summary>
        /// 创建或者更新Sqlite数据库表
        /// 在App启动的时候执行该方法，sqlite-net-pcl会根据实体类创建对应的表，如果实体类有更新，表结构也会更新，如果表结构没变，则不进行操作，sqlite-net-pcl会自动判断
        /// </summary>
        public static void CreateOrUpdateAllTablesAsync()
        {
            using (var conn = new SQLiteConnection(
                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    Consts.DataBaseName)))
            {
                conn.CreateTable<TodoItem>();
                conn.CreateTable<TaskType>();
            }
        }
        #endregion

    }
}
